package com.espressif.iot.ui.main;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import com.xiquezhijia.iot.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.espressif.iot.base.application.EspApplication;
import com.espressif.iot.base.net.rest.mesh.EspSocketClient;
import com.espressif.iot.db.IOTDeviceDBManager;
import com.espressif.iot.db.greenrobot.daos.DeviceDB;
import com.espressif.iot.device.IEspDevice;
import com.espressif.iot.model.device.EspDeviceCurtainXq;
import com.espressif.iot.model.device.EspDeviceGateway;
import com.espressif.iot.model.device.EspDevicePlugTouchsXq;
import com.espressif.iot.model.device.EspDevicePlugXq;
import com.espressif.iot.model.device.cache.EspDeviceCacheHandler;
import com.espressif.iot.type.device.EspDeviceType;
import com.espressif.iot.type.device.status.EspStatusCurtain;
import com.espressif.iot.type.device.status.EspStatusPlug;
import com.espressif.iot.type.net.IOTAddress;
import com.espressif.iot.user.IEspUser;
import com.espressif.iot.user.builder.BEspUser;
import com.espressif.iot.util.EspStrings;
import com.espressif.iot.util.InputStreamUtils;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.GrammarListener;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.speech.util.ApkInstaller;
import com.iflytek.speech.util.JsonParser;
import com.mob.tools.utils.HEX;

public class XqSpeechActivity extends Activity implements OnClickListener{
	private static final Logger log = Logger.getLogger(XqSpeechActivity.class);
	
	private TextView mycommand;
	private TextView answer;
	private ImageView mSpeechrecogize;
	// 语音识别对象
		private SpeechRecognizer mAsr;
		private Toast mToast;	
		// 缓存
		private SharedPreferences mSharedPreferences;
		// 本地语法文件
		private String mLocalGrammar = null;
		// 本地词典
		private String mLocalLexicon = null;
		// 云端语法文件 
		private String mCloudGrammar = null;
			
		private static final String KEY_GRAMMAR_ABNF_ID = "grammar_abnf_id";
		private static final String GRAMMAR_TYPE_ABNF = "abnf";
		private static final String GRAMMAR_TYPE_BNF = "bnf";

		private String mEngineType = SpeechConstant.TYPE_CLOUD;
		// 语记安装助手类
		ApkInstaller mInstaller ;
		
	//--------------------------------------------------
		// 语音合成对象
		private SpeechSynthesizer mTts;
		// 默认发音人
		private String voicer = "xiaoyan";
		// 缓冲进度
		private int mPercentForBuffering = 0;
		// 播放进度
		private int mPercentForPlaying = 0;
		//----------------------------------------------
	//以下为控制为控制设备相关的数据
		//监听添加成功的网关或者插座
	private LocalBroadcastManager mBraodcastManager;
	
	private Set<EspDeviceGateway> gatelist= new HashSet<EspDeviceGateway>();
	
	private  EspSocketClient thiclent =null;
	
	
	private   byte[] xqplugsenddata = {(byte) 0xFE,(byte) 0xE7,0,0,0x0B,0x00,
			0, 0, 0, 0, 0, 0, 0, 0,//MAC ADDR
			0, 0};
	private   byte[] result;
	private   String sendString = null;
	private ProgressDialog mDialog;
	private  List<IOTAddress> gatelocallist;
	
	private List<DeviceDB> devicelist = new ArrayList<DeviceDB>();
	private List<IEspDevice> xqdevicelist = new ArrayList<IEspDevice>();
	private List<IEspDevice> xqcommdevicelist = new ArrayList<IEspDevice>();

	private static IOTDeviceDBManager deviceDBManagerinstance = IOTDeviceDBManager.getInstance();
	
	protected IEspUser mUser;
	protected IEspDevice curespdev=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xqspeech);
		findView();
		initView();
		initDeviceList();
		mToast = Toast.makeText(this,"",Toast.LENGTH_SHORT);
		initSpeech();
		initGrammar();
		
		
		
		
		mBraodcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter(EspStrings.Action.DEVICES_ARRIVE_PULLREFRESH);
        //filter.addAction(EspStrings.Action.DEVICES_ARRIVE_STATEMACHINE);
        //filter.addAction(EspStrings.Action.LOGIN_NEW_ACCOUNT);
        //mReciever 为监听回调方法
        mBraodcastManager.registerReceiver(mReciever, filter);
        
        //这里需要进行一次扫描网关信息  广播获得IP地址  和mac地址
        scanSta();
	}
	private void scanSta()
    {

        	mUser.doActionRefreshStaDevices(false);

    }
	private void initDeviceList(){
		//devicelist.addAll(deviceDBManagerinstance.getAllDevice());
		//获取当前区域的信息
		
		mUser = BEspUser.getBuilder().getInstance();
		//加载属于该区域的设备  里面包含网关和普通设备
		xqdevicelist.clear();
		xqdevicelist.addAll(mUser.getXqDeviceList());
		if(devicelist.size()>0)
		{
			
			
			
		}
		//加载网关信息
		gatelist.addAll(EspApplication.GetGlobalGW());
		
		//过滤出普通设备来
		xqcommdevicelist.clear();
		for(IEspDevice comdev: xqdevicelist)
		{
			if(comdev.getDeviceType() != EspDeviceType.GATEWAY){
				xqcommdevicelist.add(comdev);
			}
		}
		
	}
	private void initView() {
		// TODO Auto-generated method stub
		mSpeechrecogize.setOnClickListener(this);
	}

	private void findView() {
		// TODO Auto-generated method stub
		
		mycommand = (TextView)findViewById(R.id.mycommand);
		answer = (TextView)findViewById(R.id.anstext);
		mSpeechrecogize = (ImageView)findViewById(R.id.speechbtn);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mBraodcastManager.unregisterReceiver(mReciever);
		mAsr.cancel();
		mAsr.destroy();
		if(thiclent!=null){
			try {
				thiclent.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			thiclent=null;
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		
		super.onResume();
	}
	private void initSpeech() {
		// TODO Auto-generated method stub
    	// 应用程序入口处调用，避免手机内存过小，杀死后台进程后通过历史intent进入Activity造成SpeechUtility对象为null
    			// 如在Application中调用初始化，需要在Mainifest中注册该Applicaiton
    			// 注意：此接口在非主进程调用会返回null对象，如需在非主进程使用语音功能，请增加参数：SpeechConstant.FORCE_LOGIN+"=true"
    			// 参数间使用半角“,”分隔。
    			// 设置你申请的应用appid,请勿在'='与appid之间添加空格及空转义符
    			
    			// 注意： appid 必须和下载的SDK保持一致，否则会出现10407错误
    			
    			SpeechUtility.createUtility(this, "appid=" + getString(R.string.app_id));
    				
    			// 以下语句用于设置日志开关（默认开启），设置成false时关闭语音云SDK日志打印
    			// Setting.showLogcat(false);
    			
    			// 初始化识别对象
    			mAsr = SpeechRecognizer.createRecognizer(this, null);//mInitListener);		

    			// 初始化语法、命令词  本地词典
//    			mLocalLexicon = "张海羊\n刘婧\n王锋\n";
//    			mLocalGrammar = FucUtil.readFile(this,"call.bnf", "utf-8");
    			//初始化云端语法
    			/*
    			 * "#ABNF 1.0 UTF-8;
					languagezh-CN; 
					mode voice;
					root $main;
					$main = $place1  到$place2 ;
					$place1 =  北京  |  武汉  |  南京  |  天津  |  天京  |  东京;
					$place2 =  上海  |  合肥; ";
    			 * */
    			mCloudGrammar = getString(R.string.text_isr_abnf_hint) ;
    			//mCloudGrammar = mCloudGrammar  + "  厨房灯  |  走廊开关; ";
    			String devlist ="";
    			for(IEspDevice dev : xqcommdevicelist){
    				devlist = devlist + "  " + dev.getName() +"  |";
    			}
    			//int index = devlist.lastIndexOf('|');
    			devlist = (String) devlist.subSequence(0, devlist.length()-2);
    			devlist = devlist + "; ";
    			mCloudGrammar = mCloudGrammar + devlist;
    			answer.setText("可以控制的设备有" + devlist);
    			//mCloudGrammar = FucUtil.readFile(this,"grammar_sample.abnf", "utf-8");
    			// 获取联系人，本地更新词典时使用
//    			ContactManager mgr = ContactManager.createManager(this, mContactListener);	
//    			mgr.asyncQueryAllContactsName();
    			mSharedPreferences = getSharedPreferences(getPackageName(),	MODE_PRIVATE);
    			mInstaller = new ApkInstaller(this);
    			
    			//以上为默认的初始化mAsr  下面是云端的算法构建
    			mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);
    			
    			// 云端发音人名称列表
    			//mCloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
    			//mCloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);
    					
    			//mSharedPreferences = getSharedPreferences(TtsSettings.PREFER_NAME, MODE_PRIVATE);
    			//mToast = Toast.makeText(this,"",Toast.LENGTH_SHORT);
    			
    			//mInstaller = new  ApkInstaller(this);
	}
	/**
	 * 初始化监听。
	 */
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(int code) {
			log.error("InitListener init() code = " + code);
			if (code != ErrorCode.SUCCESS) {
        		showTip("初始化失败,错误码："+code);
        	} else {
				// 初始化成功，之后可以调用startSpeaking方法
        		// 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
        		// 正确的做法是将onCreate中的startSpeaking调用移至这里
        		
			}		
		}
	};
	
	private void ItsSpeek(String tex){
		setItsParam();
		int code = mTts.startSpeaking(tex, mTtsListener);
//		/** 
//		 * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
//		 * text:要合成的文本，uri:需要保存的音频全路径，listener:回调接口
//		*/
//		String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
//		int code = mTts.synthesizeToUri(text, path, mTtsListener);
		
		if (code != ErrorCode.SUCCESS) {
			if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
				//未安装则跳转到提示安装页面
				mInstaller.install();
			}else {
				showTip("语音合成失败,错误码: " + code);	
			}
		}
	}
	/**
	 * 合成回调监听。
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener() {
		
		@Override
		public void onSpeakBegin() {
			//showTip("开始播放");
			log.error("开始播放");
		}

		@Override
		public void onSpeakPaused() {
			//showTip("暂停播放");
			log.error("暂停播放");
		}

		@Override
		public void onSpeakResumed() {
			//showTip("继续播放");
			log.error("继续播放");
		}

		@Override
		public void onBufferProgress(int percent, int beginPos, int endPos,
				String info) {
			// 合成进度
			mPercentForBuffering = percent;
			log.error(String.format(getString(R.string.tts_toast_format),
					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onSpeakProgress(int percent, int beginPos, int endPos) {
			// 播放进度
			mPercentForPlaying = percent;
			log.error(String.format(getString(R.string.tts_toast_format),
					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onCompleted(SpeechError error) {
			if (error == null) {
				showTip("播放完成");
			} else if (error != null) {
				showTip(error.getPlainDescription(true));
			}
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
			// 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
			// 若使用本地能力，会话id为null
			//	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
			//		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
			//		Log.d(TAG, "session id =" + sid);
			//	}
		}
	};
	/**
	 * 参数设置
	 * @param param
	 * @return 
	 */
	private void setItsParam(){
		// 清空参数
		mTts.setParameter(SpeechConstant.PARAMS, null);
		// 根据合成引擎设置相应参数
		if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
			// 设置在线合成发音人
			mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
		}else {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
			// 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
			mTts.setParameter(SpeechConstant.VOICE_NAME, "");
		}
		//设置合成语速
		mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50"));
		//设置合成音调
		mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50"));
		//设置合成音量
		mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50"));
		//设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3"));
		
		// 设置播放合成音频打断音乐播放，默认为true
		mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
		
		// 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		// 注：AUDIO_FORMAT参数语记需要更新版本才能生效
		mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
		mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/tts.wav");
	}
	int ret = 0;
	String mContent = "";
	private void initGrammar(){
	
		showTip("上传预设关键词/语法文件");
		// 本地-构建语法文件，生成语法id
		if (mEngineType.equals(SpeechConstant.TYPE_LOCAL)) {
			log.error("上传本地的关键词/语法文件是" + mLocalGrammar);
			//((EditText)findViewById(R.id.isr_text)).setText(mLocalGrammar);
			mContent = new String(mLocalGrammar);
			mAsr.setParameter(SpeechConstant.TEXT_ENCODING,"utf-8");
			//指定引擎类型
			mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
			ret = mAsr.buildGrammar(GRAMMAR_TYPE_BNF, mContent, mLocalGrammarListener);
			if(ret != ErrorCode.SUCCESS){
				if(ret == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
					//未安装则跳转到提示安装页面
					mInstaller.install();
				}else {
					showTip("语法构建失败,错误码：" + ret);
				}
			}
		}
		// 在线-构建语法文件，生成语法id
		else {	
			//((EditText)findViewById(R.id.isr_text)).setText(mCloudGrammar);
			log.error("上传云端的关键词/语法文件是" + mCloudGrammar);
			mContent = new String(mCloudGrammar);
			//指定引擎类型  为cloud
			mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
			mAsr.setParameter(SpeechConstant.TEXT_ENCODING,"utf-8");
		    ret = mAsr.buildGrammar(GRAMMAR_TYPE_ABNF, mContent, mCloudGrammarListener);
			if(ret != ErrorCode.SUCCESS)
				showTip("语法构建失败,错误码：" + ret);
		}
	}
	/**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(int code) {
			//Log.d(TAG, "SpeechRecognizer init() code = " + code);
			log.error("SpeechRecognizer init() code = " + code);
			if (code != ErrorCode.SUCCESS) {
        		showTip("初始化失败,错误码："+code);
        	}
		}
    };
	/**
     * 本地构建语法监听器。
     */
	private GrammarListener mLocalGrammarListener = new GrammarListener() {
		@Override
		public void onBuildFinish(String grammarId, SpeechError error) {
			if(error == null){
				showTip("语法构建成功：" + grammarId);
			}else{
				showTip("语法构建失败,错误码：" + error.getErrorCode());
			}			
		}
	};
	/**
     * 云端构建语法监听器。
     */
	private GrammarListener mCloudGrammarListener = new GrammarListener() {
		@Override
		public void onBuildFinish(String grammarId, SpeechError error) {
			if(error == null){
				String grammarID = new String(grammarId);
				Editor editor = mSharedPreferences.edit();
				if(!TextUtils.isEmpty(grammarId))
					editor.putString(KEY_GRAMMAR_ABNF_ID, grammarID);
				editor.commit();
				showTip("语法构建成功：" + grammarId);
			}else{
				showTip("语法构建失败,错误码：" + error.getErrorCode());
			}			
		}
	};
	/**
     * 识别监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {
        
        @Override
        public void onVolumeChanged(int volume, byte[] data) {
        	showTip("当前正在说话，音量大小：" + volume);
        	//Log.d(TAG, "返回音频数据："+data.length);
        	log.error("返回音频数据："+data.length);
        }
        
        @Override
        public void onResult(final RecognizerResult result, boolean isLast) {
        	if (null != result) {
        		//Log.d(TAG, "recognizer result：" + result.getResultString());
        		log.error("recognizer result：" + result.getResultString());
        		String text ;
        		if("cloud".equalsIgnoreCase(mEngineType)){
        			text = JsonParser.parseGrammarResult(result.getResultString());
        		}else {
        			text = JsonParser.parseLocalGrammarResult(result.getResultString());
        		}
        		
        		// 显示
        		//((EditText)findViewById(R.id.isr_text)).setText(text); 
        		log.error("recognizer result : "  + text);
        		if(text.contains("没有匹配结果")){
        			ItsSpeek("对不起，我不明白你的意思");
        			answer.setText("对不起，我不明白你的意思");
        		}
        		else
        		{
        			ProcessCmd(text);
        			mycommand.setText(text);
        		}
        	} else {
        		//Log.d(TAG, "recognizer result : null");
        		log.error("recognizer result : null");
        	}	
        }
        
        @Override
        public void onEndOfSpeech() {
        	// 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
        	showTip("结束说话");
        }
        
        @Override
        public void onBeginOfSpeech() {
        	// 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
        	showTip("开始说话");
        }

		@Override
		public void onError(SpeechError error) {
			showTip("onError Code："	+ error.getErrorCode());
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
			// 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
			// 若使用本地能力，会话id为null
			//	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
			//		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
			//		Log.d(TAG, "session id =" + sid);
			//	}
		}

    };
    /**
	 * 参数设置
	 * @param param
	 * @return 
	 */
	public boolean setParam(){
		boolean result = false;
		//设置识别引擎
		mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
		//设置返回结果为json格式
		mAsr.setParameter(SpeechConstant.RESULT_TYPE, "json");

		if("cloud".equalsIgnoreCase(mEngineType))
		{
			String grammarId = mSharedPreferences.getString(KEY_GRAMMAR_ABNF_ID, null);
			
			if(TextUtils.isEmpty(grammarId))
			{
				result =  false;
			}else {
				//设置云端识别使用的语法id
				mAsr.setParameter(SpeechConstant.CLOUD_GRAMMAR, grammarId);
				result =  true;
			}
		}
		else
		{
			//设置本地识别使用语法id
			mAsr.setParameter(SpeechConstant.LOCAL_GRAMMAR, "call");
			//设置本地识别的门限值
			mAsr.setParameter(SpeechConstant.ASR_THRESHOLD, "30");
			result = true;
		}
		
		// 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		// 注：AUDIO_FORMAT参数语记需要更新版本才能生效
//		mAsr.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
//		mAsr.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/asr.wav");
		return result;
	}
	private void showTip(final String str) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mToast.setText(str);
				mToast.show();
			}
		});
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == mSpeechrecogize){
			if (!setParam()) {
				showTip("请先构建语法。");
				return;
			};
			
			ret = mAsr.startListening(mRecognizerListener);
			if (ret != ErrorCode.SUCCESS) {
				if(ret == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
					//未安装则跳转到提示安装页面
					mInstaller.install();
				}else {
					showTip("识别失败,错误码: " + ret);	
				}
			}
			
		// 停止识别
		}
	}
	  private BroadcastReceiver mReciever = new BroadcastReceiver()
	    {
	        
	        @Override
	        public void onReceive(Context context, Intent intent)
	        {
	            final String action = intent.getAction();
	           
	            if(action.equals(EspStrings.Action.DEVICES_ARRIVE_PULLREFRESH)){
	            	Toast.makeText(getApplicationContext(), "扫描网关结束", Toast.LENGTH_SHORT).show();
	            	//更新网关的IP信息
	            	gatelocallist = EspDeviceCacheHandler.getInstance().GetGateIp();
	            	
	            	if(gatelocallist!=null && gatelocallist.size()>0){
	            		for(IOTAddress gate: gatelocallist){
	            			for(EspDeviceGateway owngate: gatelist){
	            				if(owngate.getBssid().equals(gate.getBSSID())){
	            					
	            					String hostname = gate.getInetAddress().getHostName();
	            					owngate.setInetAddress(gate.getInetAddress());
	            					owngate.SetInetAddress(gate.getInetAddress());
	            				}
	            			}
	            		}
	            	}
	            	updatedevInetAddress();
	            	//releaseDialog();
	            	ItsSpeek(answer.getText().toString());
	            }
	        }

			private void updatedevInetAddress() {
				// TODO Auto-generated method stub
				if(gatelist!=null && gatelist.size()>0){
          		
          		
          		//update the no gateway ip 
          		for(EspDeviceGateway owngate: gatelist){
          			if(null == owngate.getInetAddress())
          				continue;
          			for(IEspDevice comdev:xqdevicelist){
          				if(comdev.getDeviceType() == EspDeviceType.GATEWAY)
          					continue;
          				if(comdev.getBssid().equals(owngate.getBssid())){
          					comdev.setInetAddress(owngate.getInetAddress());
          				}
          			}
          		}
          	}
			}
	        
	    };
	    int pos;
	    
	    public void ProcessCmd(String result){
			// TODO Auto-generated method stub
	    	boolean  isoncmd = false;
			log.error("控制命令为" + result);
			answer.setText(result);
			String devname="";
			curespdev = null;
			String cmdprefix = "【结果】";
			String cmdsuffix = "【置信度】";
			String cmdopen = "打开";
			String cmdclose = "关闭";
			if(result.contains(cmdprefix)){
				int index =result.indexOf(cmdopen);
				if(index ==-1){
					index =result.indexOf(cmdclose);
				}
				if(-1 == index){
					showTip("命令不合法");
					return ;
				}
				if(result.contains(cmdopen)){
					isoncmd =true;
				}
				else if(result.contains(cmdclose)){
					isoncmd = false;
				}
				int endex = result.indexOf(cmdsuffix);
				devname = result.substring(index+cmdopen.length(), endex);
				
				//get the dev obj by devname;
				curespdev = Getdevbyname(devname);
			}
			
			if(curespdev !=null){
				//【结果】【置信度】
				
				//mIEspDevice = xqdevicelist.get(pos);
				//curespdev = mIEspDevice;
				IEspDevice mIEspDevice = curespdev;
				if(curespdev.getDeviceType() == EspDeviceType.GATEWAY){
					//准备往该网关添加设备
				/**
				 * 	把区域名字传递到下一个activity  并且把该网关的IP信息往下传递  方便做测试使用  testonoff
				 * */
				}
				else{
					

					log.error(curespdev.getName() +"::" + curespdev.getInetAddress());
					if(thiclent ==null && curespdev.getInetAddress()!=null){
						new ConnetSocet(mIEspDevice.getInetAddress()).start();
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					if(thiclent !=null){
						String devicekey = mIEspDevice.getKey();
						String bssidstr  = devicekey.substring(0, 16);
						
						byte[]  bssid = HEX.decodeHexString(bssidstr);
						bssidstr = "";
						for(int j=0; j<8; j++){
							bssidstr = bssidstr  + " " + bssid[j];
							xqplugsenddata[6+j]=bssid[j];
						}
						Log.e("plug or kaiguan's bssid", bssidstr);
						
						if(mIEspDevice.getDeviceType() == EspDeviceType.PLUG_XQ)
						{
							EspStatusPlug statusPlug;
							 
							 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)mIEspDevice).getStatusPlug();
							
							boolean ison = !statusPlug.isOn();
							if(ison && isoncmd){
								showTip("设备已经打开");
								return;
							}else if(!ison && !isoncmd){
								showTip("设备已经关闭");
								return;
							}
							xqplugsenddata[14] = (byte) ((ison==true)?1:0);
							
						}
						else if(mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH)
						{
							EspStatusPlug statusPlug;
							 
							 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)mIEspDevice).getStatusPlug();
							
							boolean ison = !statusPlug.isOn();
							xqplugsenddata[14] = (byte) ((ison==true)?0x22:0x20);
							 if(isoncmd && ison){
									showTip("设备已经打开");
									return;
							}else if(!isoncmd && !ison){
								showTip("设备已经关闭");
								return;
							}
						}else if(mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_2
								|| mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_3
								|| mIEspDevice.getDeviceType() == EspDeviceType.PLUGTOUCH_4){
							
							EspStatusPlug statusPlug;
							EspDevicePlugTouchsXq devtouchs =(EspDevicePlugTouchsXq)mIEspDevice; 
							 statusPlug =(EspStatusPlug) ((EspDevicePlugTouchsXq)mIEspDevice).getStatusPlug();
							 boolean ison = !statusPlug.isOn();
							 int posmove=0;
							 if (devtouchs.getPlugtouchnum()==1)
								 posmove = 2;
							 else if(devtouchs.getPlugtouchnum()==2)
								 posmove = 1;
							 else
								 posmove = devtouchs.getPlugtouchnum();
							 
							 int openvalue = 0x11<<posmove ;
							 int closevalue = 0x10<<posmove;
							 if(isoncmd && (openvalue&0x0f)!=0){
									showTip("设备已经打开");
									return;
								}else if(!isoncmd && (openvalue&0x0f)==0){
									showTip("设备已经关闭");
									return;
								}
							 xqplugsenddata[14] = (byte) ((ison==true)?openvalue:closevalue);
							 
							
						}else if(mIEspDevice.getDeviceType() == EspDeviceType.CURTAIN)
						{
							EspStatusCurtain statuscurtain;
							statuscurtain =(EspStatusCurtain) ((EspDeviceCurtainXq)mIEspDevice).getStatusCurtain();
							Log.e("CURTAIN or CURTAIN's bssid", bssidstr);
							int mison = statuscurtain.isOn();
							if(mison ==2)
								xqplugsenddata[14] = 1;
							else if(mison ==1)
								xqplugsenddata[14] = 2;
							
							if(isoncmd && mison==1){
								showTip("设备已经打开");
								return;
							}else if(!isoncmd && mison==2){
								showTip("设备已经关闭");
								return;
							}
						
						}
						byte cheksum=0;
						for(int i=4; i<15; i++){
							cheksum += xqplugsenddata[i]; 
						}
						xqplugsenddata[15] = cheksum;
						
						try {
							sendString = new String( xqplugsenddata , "ISO-8859-1" );
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						new Plugonoff(this).execute(true);
					}else{
						Toast.makeText(this, R.string.esp_configure_direct_result_failed, Toast.LENGTH_SHORT).show();
			            return ;
					}
				}
			}
			
		}   
	    private IEspDevice  Getdevbyname(String devname) {
			// TODO Auto-generated method stub
	    	if(xqcommdevicelist!=null && xqcommdevicelist.size()>0)
	    	for(IEspDevice curdev: xqcommdevicelist){
	    		if(curdev.getName().equals(devname))
	    			return curdev;
	    	}
	    	
			return null;
		}
		private class Plugonoff extends AsyncTask<Boolean, Void, Boolean> implements OnDismissListener
	    {
	        private Activity mActivity;
	        
	        private ProgressDialog mDialog;
	        
	      
	        
	        public Plugonoff(Activity activity)
	        {
	            mActivity = activity;
	           
	        }
	        
	       
	        @Override
	        protected void onPreExecute()
	        {
	           
	            
	            showDialog();
	        }
	        
	        @Override
	        protected Boolean doInBackground(Boolean... ison)
	        {
	        	//Log.e("getInetAddress", "selectedgate.getInetAddress().getHostName()=" + selectedgate.getInetAddress().getHostAddress());
	        	try {
	        		Log.e("Plugonoff------", sendString);
					
					thiclent.writeRequest(sendString);
					thiclent.setSoTimeout(3000);
					//等待响应数据返回
					String result = thiclent.readResponse();
					byte[] resultbyte = result.getBytes(InputStreamUtils.DEFAULT_CHARSET);
					if(curespdev.getDeviceType().getSerial() == EspDeviceType.PLUG_XQ.getSerial())
					{
						
						if(resultbyte.length ==16){
							if(resultbyte[0] == (byte)0xfe && resultbyte[1]==(byte)0x7e){
								EspStatusPlug statusPlug;
								 
								 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)curespdev).getStatusPlug();
								Log.e("EspDevicePlug", "(EspDevicePlugXq)curespdev).getStatusPlug()=" + statusPlug);
								
				                if(resultbyte[14] ==1)
									statusPlug.setIsOn(true);
								else if(resultbyte[14] ==0)
									statusPlug.setIsOn(false);
							}
						}
						return true;
					}
					else if(curespdev.getDeviceType() == EspDeviceType.PLUGTOUCH)
					{
						
						if(resultbyte.length ==16){
							if(resultbyte[0] == (byte)0xfe && resultbyte[1]==(byte)0x7e){
								EspStatusPlug statusPlug;
								 
								 statusPlug =(EspStatusPlug) ((EspDevicePlugXq)curespdev).getStatusPlug();
								Log.e("EspDevicePlug", "(EspDevicePlugXq)curespdev).getStatusPlug()=" + statusPlug);
								
				                if(resultbyte[14] ==0x22)
									statusPlug.setIsOn(true);
								else if(resultbyte[14] ==0x20)
									statusPlug.setIsOn(false);
							}
						}
						return true;
					}
					else if(curespdev.getDeviceType() == EspDeviceType.PLUGTOUCH_2
							|| curespdev.getDeviceType() == EspDeviceType.PLUGTOUCH_3
							|| curespdev.getDeviceType() == EspDeviceType.PLUGTOUCH_4)
					{
						
						if(resultbyte.length ==16){
							if(resultbyte[0] == (byte)0xfe && resultbyte[1]==(byte)0x7e){
							
								EspStatusPlug statusPlug;
								EspDevicePlugTouchsXq mdev = (EspDevicePlugTouchsXq)curespdev;
								 statusPlug =(EspStatusPlug) ((EspDevicePlugTouchsXq)curespdev).getStatusPlug();
								Log.e("EspDevicePlug", "(EspDevicePlugXq)curespdev).getStatusPlug()=" + statusPlug);
								int respvalueOn = 0x11;
								if (mdev.getPlugtouchnum()==1)
									respvalueOn = 0x11<<2;
								 else if(mdev.getPlugtouchnum()==2)
									 respvalueOn = 0x11<<1;
								 else
									 respvalueOn = 0x11<<mdev.getPlugtouchnum();
								//int respvalueOff = 0x10<<mdev.getPlugtouchnum();
				                if((resultbyte[14] & (byte)respvalueOn & 0x0f) !=0  )
									statusPlug.setIsOn(true);
								else if((resultbyte[14] & (byte)respvalueOn & 0x0f) ==0  )
									statusPlug.setIsOn(false);
							}
						}
						
						return true;
					}
					else if(curespdev.getDeviceType() == EspDeviceType.CURTAIN)
					{
						
						if(resultbyte.length ==16){
							if(resultbyte[0] == (byte)0xfe && resultbyte[1]==(byte)0x7e){
							
								EspStatusCurtain statuscurtain;
								EspDeviceCurtainXq mdev = (EspDeviceCurtainXq)curespdev;
								
								statuscurtain =(EspStatusCurtain) ((EspDeviceCurtainXq)curespdev).getStatusCurtain();
								
								Log.e("EspDevicePlug", "(EspDevicePlugXq)curespdev).getStatusPlug()=" + statuscurtain);
								
								statuscurtain.setIsOn(resultbyte[14]);
								
							}
						}
						
						return true;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	return false;
	        }
	        
	        @Override
	        protected void onPostExecute(Boolean result)
	        {
	            //log.debug("DeviceTask result = " + result);
	            releaseDialog();
	           
	            if(result == true){
	            	//mdeviceadapter.notifyDataSetChanged();
	            	showTip("控制成功");
	            	ItsSpeek("控制成功");
	            }else{
	            	ItsSpeek("控制失败");
	            }
	        }
	        
	        private void showDialog()
	        {
	            mDialog = new ProgressDialog(mActivity);
	            mDialog.setMessage(getString(R.string.esp_device_task_dialog_message));
	            mDialog.setCanceledOnTouchOutside(false);
	            mDialog.setOnDismissListener(this);
	            mDialog.show();
	        }
	        
	        private void releaseDialog()
	        {
	            if (mDialog != null)
	            {
	                mDialog.dismiss();
	                mDialog = null;
	            }
	        }
	        
	        @Override
	        public void onDismiss(DialogInterface dialog)
	        {
	            cancel(true);
	            mDialog = null;
	        }

			
	    }
		
		 private class ConnetSocet extends Thread{
		    	InetAddress host;
		    	public ConnetSocet(InetAddress iphost){
		    		host =iphost;
		    	}
				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					thiclent = new EspSocketClient();
					thiclent.connect(host.getHostAddress(), 1206);
					
				}
				
			}
}
